package cn.dankal.flyaudio.presenter;

import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jyj.recruitment.wxapi.PayUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

import androidx.annotation.NonNull;
import api.ShopUserServiceFactory;
import cn.dankal.basiclib.pojo.AddressEntity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.CreateOrderPreviewEntity;
import cn.dankal.basiclib.pojo.WexinPayResult;
import cn.dankal.basiclib.pojo.req.CreateOrderReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.contract.ConfirmOrderContract;
import cn.dankal.flyaudio.store.PayResultActivity;

public class ConfirmOrderPresenter implements ConfirmOrderContract.Presenter {

    public static final int PAY_TYPE_WECHAT = 1;

    public static final int PAY_TYPE_ALIPAY = 2;

    public static final int PAY_TYPE_NO_PAY = 3;

    private ConfirmOrderContract.View mView;

    private String orderId = "";

    @Override
    public void attachView(@NonNull ConfirmOrderContract.View view) {
        this.mView = view;
    }

    @Override
    public void detachView() {
        this.mView = null;
    }

    @Override
    public void getMyAddress() {
        ShopUserServiceFactory.getUserAddress().subscribe(new AbstractSubscriber<BaseResponse<List<AddressEntity>>>(mView) {
            @Override
            public void onNext(BaseResponse<List<AddressEntity>> listBaseResponse) {
                mView.handleAddressList(listBaseResponse.getData());
            }
        });
    }

    public String getUuid(){
        return orderId;
    }

    @Override
    public void createOrder(CreateOrderReq req, int payType) {
        mView.showLoadingDialog();
        if(payType==ConfirmOrderPresenter.PAY_TYPE_NO_PAY){
            req.setIsAllJf("1");
        }
        ShopUserServiceFactory.createOrder(req)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(mView) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        ToastUtils.showShort("下单成功");
                        orderId = objectBaseResponse.getData();
                        mView.dismissLoadingDialog();
                        if (payType == PAY_TYPE_ALIPAY) {
                            alipay(objectBaseResponse.getData());
                        } else if (payType == PAY_TYPE_WECHAT) {
                            wechatPay(objectBaseResponse.getData());
                        } else if (payType == PAY_TYPE_NO_PAY) {
                            LiveEventBus.get("create_order_success", String.class).post("");
                            LiveEventBus.get("ShopCarNum", String.class).post("");
                            mView.finishActivity();
                            Intent intent = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                            intent.putExtra("isPaySuccess", true);
                            intent.putExtra("orderUuid", objectBaseResponse.getData());
                            ActivityUtils.startActivity(intent);
                        }
                    }
                });
    }


    @Override
    public void createOrderPreview(CreateOrderReq req) {
        mView.showLoadingDialog();
        ShopUserServiceFactory.createOrderPreview(req)
                .subscribe(new AbstractSubscriber<BaseResponse<CreateOrderPreviewEntity>>(mView) {
                    @Override
                    public void onNext(BaseResponse<CreateOrderPreviewEntity> objectBaseResponse) {
//                        ToastUtils.showShort("下单成功");
                        mView.handlePreview(objectBaseResponse.getData());
                        mView.dismissLoadingDialog();
                    }
                });
    }

    @Override
    public void wechatPay(String uuid) {
        mView.showLoadingDialog();
        ShopUserServiceFactory.wx(uuid)
                .subscribe(new AbstractSubscriber<BaseResponse<WexinPayResult>>(mView) {
                    @Override
                    public void onNext(BaseResponse<WexinPayResult> objectBaseResponse) {
                        mView.dismissLoadingDialog();
                        Log.d("ConfirmOrderPresenter",JSON.toJSONString(objectBaseResponse));
                        IWXAPI iwxapi = WXAPIFactory.createWXAPI(FlyApplication.getContext(), objectBaseResponse.getData().getAppid(), true);
                        iwxapi.registerApp(objectBaseResponse.getData().getAppid());
                        SharePreferenceManager.setCachedAppKey(objectBaseResponse.getData().getAppid());
                        PayReq payReq = PayUtils.wechatPay(JSON.toJSONString(objectBaseResponse.getData()));
                        Log.d("ConfirmOrderPresenter",JSON.toJSONString(payReq));
                        iwxapi.sendReq(payReq);
                    }
                });
    }

    @Override
    public void alipay(String uuid) {
        mView.showLoadingDialog();
        ShopUserServiceFactory.alipay(uuid)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(mView) {
                    @Override
                    public void onNext(BaseResponse<String> createOrderPreviewEntityBaseResponse) {
                        mView.dismissLoadingDialog();
                        Log.d("ConfirmOrderPresenter",JSON.toJSONString(createOrderPreviewEntityBaseResponse));
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean isSuccess = PayUtils.aliPay(ActivityUtils.getTopActivity(),createOrderPreviewEntityBaseResponse.getData());
                                LiveEventBus.get("create_order_success", String.class).post("");
                                LiveEventBus.get("ShopCarNum", String.class).post("");
                                if(isSuccess){
                                    Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                                    jump.putExtra("isPaySuccess", true);
                                    jump.putExtra("orderUuid", uuid);
                                    ActivityUtils.startActivity(jump);
                                    mView.finishActivity();
                                    Log.d("ConfirmOrderPresenter","支付成功");
                                }else {
                                    Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                                    jump.putExtra("isPaySuccess", false);
                                    jump.putExtra("orderUuid", uuid);
                                    ActivityUtils.startActivity(jump);
                                    mView.finishActivity();
                                    Log.d("ConfirmOrderPresenter","支付失败");
                                }
                            }
                        }).start();
                    }
                });

    }
}
